library flutter_city4_package;

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'city4_entity.dart';
import 'package:flutter_city4_package/generated/json/base/json_convert_content.dart';

class CityModel{
  String city1;
  String city2;
  String city3;
  String city4;
  CityModel({this.city1, this.city2, this.city3, this.city4});

}

/// todo：城市选择器
class CitySelect extends StatefulWidget {
  Function(CityModel) onChang;
  bool isCity4; //
  CitySelect({Key key,this.onChang,this.isCity4:false}) : super(key: key);

  @override
  _CitySelectState createState() => _CitySelectState();
}

class _CitySelectState extends State<CitySelect> {

  int select1 = 0;
  int select2 = 0;
  int select3 = 0;
  int select4 = 0;

  PageController pagecontroller1;
  PageController pagecontroller2;
  PageController pagecontroller3;
  PageController pagecontroller4;

  City4Entity city4entity = City4Entity();
  CityModel cityModel = CityModel();
  List<Widget> list = [];

  @override
  void initState() {
    pagecontroller1 = new PageController(viewportFraction: 0.22,initialPage: 0);
    pagecontroller2 = new PageController(viewportFraction: 0.22,initialPage: 0);
    pagecontroller3 = new PageController(viewportFraction: 0.22,initialPage: 0);
    pagecontroller4 = new PageController(viewportFraction: 0.22,initialPage: 0);
    getLocalJson();
    // TODO: implement initState
    super.initState();
  }

  /// todo: 读取本地json文件
  void getLocalJson() async {
    Map<String, dynamic> map = jsonDecode(await rootBundle.loadString("packages/flutter_city4_package/assets/city4.json"));
    city4entity = JsonConvert.fromJsonAsT(map);
    setState(() { });
  }

  @override
  Widget build(BuildContext context) {

    if(city4entity.children!=null){
      list = [
        itemWidget(
          pageWidget: PageView.builder(
            itemCount: city4entity.children.length,
            controller: pagecontroller1,
            scrollDirection: Axis.vertical,
            pageSnapping: true,
            physics: AlwaysScrollableScrollPhysics(),
            itemBuilder: (ctx ,index ){
              return Center(child: Text('${city4entity.children[index].name}',maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(color: select1 == index ? Colors.black : Colors.grey[600],fontWeight: select1 == index ? FontWeight.bold : FontWeight.normal,fontSize: select1 == index ? 15:13),));
            },
            onPageChanged: (int index) {
              setState(() {
                select1 = index;
                select2 = 0;
                select3 = 0;
                select4 = 0;
                pagecontroller2.jumpToPage(0);
                pagecontroller3.jumpToPage(0);
                if(widget.isCity4)pagecontroller4.jumpToPage(0);
                if(widget.onChang != null){
                  cityModel.city1 = city4entity.children[index].name;
                  cityModel.city2 = city4entity.children[select1].children[index].name;
                  cityModel.city3 = city4entity.children[select1].children[select2].children[index].name;
                  cityModel.city4 = city4entity.children[select1].children[select2].children[select3].children[index].name;
                  widget.onChang(cityModel);
                }
              });
            },
          ),
        ),

        itemWidget(
          pageWidget: PageView.builder(
            itemCount: city4entity.children[select1].children.length,
            controller: pagecontroller2,
            scrollDirection: Axis.vertical,
            pageSnapping: true,
            physics: AlwaysScrollableScrollPhysics(),
            itemBuilder: (ctx ,index ){
              return Center(child: Text('${city4entity.children[select1].children[index].name}',maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(color: select2 == index ? Colors.black : Colors.grey[600],fontWeight: select2 == index ? FontWeight.bold : FontWeight.normal,fontSize: select2 == index ? 15:13),));
            },
            onPageChanged: (int index) {
              setState(() {
                select2 = index;
                pagecontroller3.jumpToPage(0);
                if(widget.isCity4)pagecontroller4.jumpToPage(0);
                if(widget.onChang != null){
                  cityModel.city1 = city4entity.children[index].name;
                  cityModel.city2 = city4entity.children[select1].children[index].name;
                  cityModel.city3 = city4entity.children[select1].children[select2].children[index].name;
                  cityModel.city4 = city4entity.children[select1].children[select2].children[select3].children[index].name;
                  widget.onChang(cityModel);
                }
              });
            },
          ),
        ),

        itemWidget(
          pageWidget: PageView.builder(
            itemCount: city4entity.children[select1].children[select2].children.length,
            controller: pagecontroller3,
            scrollDirection: Axis.vertical,
            pageSnapping: true,
            physics: AlwaysScrollableScrollPhysics(),
            itemBuilder: (ctx ,index ){
              return Center(child: Text('${city4entity.children[select1].children[select2].children[index].name}',maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(color: select3 == index ? Colors.black : Colors.grey[600],fontWeight: select3 == index ? FontWeight.bold : FontWeight.normal,fontSize: select3 == index ? 15:13),));
            },
            onPageChanged: (int index) {
              setState(() {
                select3 = index;
                if(widget.isCity4)pagecontroller4.jumpToPage(0);
                if(widget.onChang != null){
                  cityModel.city1 = city4entity.children[index].name;
                  cityModel.city2 = city4entity.children[select1].children[index].name;
                  cityModel.city3 = city4entity.children[select1].children[select2].children[index].name;
                  cityModel.city4 = city4entity.children[select1].children[select2].children[select3].children[index].name;
                  widget.onChang(cityModel);
                }
              });
            },
          ),
        ),
      ];
      /// 展示4级时 插入第4级
      if(widget.isCity4){
        list.add(
          itemWidget(
            pageWidget: PageView.builder(
              itemCount: city4entity.children[select1].children[select2].children[select3].children.length,
              controller: pagecontroller4,
              scrollDirection: Axis.vertical,
              pageSnapping: true,
              physics: AlwaysScrollableScrollPhysics(),
              itemBuilder: (ctx ,index ){
                return Center(child: Text('${city4entity.children[select1].children[select2].children[select3].children[index].name}',maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(color: select4 == index ? Colors.black : Colors.grey[600],fontWeight: select4 == index ? FontWeight.bold : FontWeight.normal,fontSize: select4 == index ? 15:13),));
              },
              onPageChanged: (int index) {
                setState(() {
                  select4 = index;
                  if(widget.onChang != null){
                    cityModel.city1 = city4entity.children[index].name;
                    cityModel.city2 = city4entity.children[select1].children[index].name;
                    cityModel.city3 = city4entity.children[select1].children[select2].children[index].name;
                    cityModel.city4 = city4entity.children[select1].children[select2].children[select3].children[index].name;
                    widget.onChang(cityModel);
                  }
                });
              },
            ),
          ),
        );
      }
    }

    return  Container(
      height: 230,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: list,
      ),
    );
  }

  Widget itemWidget({Widget pageWidget}){
    return Expanded(child: Container(
      alignment: Alignment.center,
      child: Stack(
        children: [
          bgSelect(),
          pageWidget,
        ],
      ),
    ),);
  }

  /// 选择框
  Widget bgSelect(){
    return Center(
      child: Container(
        height: 50,
        decoration: BoxDecoration(
          border: Border(top: BorderSide(width: 0.5,color: Colors.grey[400]),bottom: BorderSide(width: 0.5,color: Colors.grey[400])),
        ),
      ),
    );
  }
}

/// todo：[isCity4] = true 四级联动，[isCity4] = false 三级联动
/// todo：[topWidget] = 顶部可自定义
/// todo：[onChang] 回调  [onOK] 确认键 ， [topWidget] 设置后 [onChang]、[onOK] 无效
void openBottomCitySelect({BuildContext context,Function(CityModel) onChang,Function(CityModel) onOK,bool isCity4,Widget topWidget}){
  CityModel cityModel = CityModel(city1: "北京市" ,city2: "市辖区",city3: "东城区",city4: "东华门街道") ;
  var textStyle = TextStyle(color: Colors.blue,fontSize: 16);
  showModalBottomSheet(context: context, builder: (context){
    return StatefulBuilder(builder: (context,setSet){
      return Container(
        color: Colors.white,
        height: 300,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              child: topWidget ?? Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  MaterialButton(onPressed: ()=>Navigator.pop(context),child: Text("取消",style: textStyle,),),

                  MaterialButton(onPressed: (){
                    if(onOK != null) onOK(cityModel);
                    Navigator.pop(context);
                  },child: Text("确定",style: TextStyle(color: Colors.blue,fontSize: 16),),),
                ],
              ),
              color: Colors.grey[100],
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 15,),
              child: CitySelect(
                isCity4: isCity4,
                onChang:  (v){
                  cityModel = v;
                  if(onChang!=null) onChang(cityModel);
                },
              ),)
          ],
        ),
      );
    });
  });
}



